package com.appkubes.fintech.admin.task.job;

import com.appkubes.fintech.admin.task.dao.FintechTaskLogDao;
import com.appkubes.fintech.common.util.SpringContextHolder;
import com.appkubes.fintech.core.po.FintechTaskInfo;
import com.appkubes.fintech.core.po.FintechTaskLog;
import com.appkubes.fintech.core.pojo.FintechTaskLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/***
* @Description:
* @Param:  定时任务
* @Author: XQC
* @Date: 2019/4/23 11:25
*/
@Async
@Slf4j
public class ExecutionJob extends QuartzJobBean {
    public static final String JOB_KEY = "JOB_KEY";
    @Resource(name = "scheduler")
    private Scheduler scheduler;


    @Autowired
    private ExecutorService executorService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        FintechTaskInfo quartzJob = (FintechTaskInfo) context.getMergedJobDataMap().get(JOB_KEY);
        // 获取spring bean

        FintechTaskLogDao quartzLogRepository = SpringContextHolder.getBean("fintechTaskLogDao");
        QuartzManage quartzManage = SpringContextHolder.getBean("quartzManage");
        FintechTaskLog quartzLog = new FintechTaskLog();
        quartzLog.setId(UUID.randomUUID().toString().replace("-",""));
        quartzLog.setJobName(quartzJob.getName());
        quartzLog.setBeanName(quartzJob.getBeanName());
        quartzLog.setMethodName(quartzJob.getMethodName());
        quartzLog.setParams(quartzJob.getParams());
        long startTime = System.currentTimeMillis();
        quartzLog.setCronExpression(quartzJob.getTaskTime());
        try {
            // 执行任务
            log.info("任务准备执行，任务名称：{}", quartzJob.getName());
            QuartzRunnable task = new QuartzRunnable(quartzJob.getBeanName(), quartzJob.getMethodName(),
                    quartzJob.getParams());
            Future<?> future = executorService.submit(task);
            future.get();
            long times = System.currentTimeMillis() - startTime;
            quartzLog.setTime(times);
            quartzJob.setCreateTime(new Date());
            // 任务状态
            quartzJob.setUpdateTime(new Date());
            quartzLog.setIsSuccess(true);
            log.info("任务执行完毕，任务名称：{} 总共耗时：{} 毫秒", quartzJob.getName(), times);
        } catch (Exception e) {
            log.error("任务执行失败，任务名称：{}" + quartzJob.getName(), e);
            long times = System.currentTimeMillis() - startTime;
            quartzLog.setTime(times);
            // 任务状态 0：成功 1：失败
            quartzLog.setIsSuccess(false);
            quartzLog.setExceptionDetail(e.getMessage());
            //出错就暂停任务
            quartzManage.pauseJob(quartzJob);
            quartzJob.setCreateTime(new Date());
            // 任务状态
            quartzJob.setUpdateTime(new Date());
            //更新状态
            quartzJob.setStatus(0);
        } finally {
            quartzLogRepository.insert(quartzLog);
        }
    }
}
